; main.asm
; Main module

	.include "global.inc"
	.include "colors.inc" 

	.include "frame.inc"
	.include "sprites.inc"
	.include "sound.inc"
	.include "game.inc"
	.include "eightplay.inc"

	.export main
	.export check_key
	.export adaptr
	
	.import initirq
	.import execirq
	.import waitframe
	.import show_winner

	IRQ_TAIL = $EB15
	_DEBUG_IRQ =1

	.segment "JMPTBL"

stateptr:	.word setupgame
	
	.segment "CODE"
	
main:		; setup joystick handler
			bne @joy4
			jsr jinit8
			jmp @skip4
@joy4:		jsr jinit4
@skip4:
			; sound off
			jsr soundoff
			; setup interrupt handler
			jsr initirq
			lda #<main_irq
			ldx #>main_irq
			sta IRQ_VECTOR
			stx IRQ_VECTOR+1
			; setup screen
			jsr initfrm
			; setup sprites
			jsr initspr
			; setup game state
			jsr initgame
			; init frame debug
.ifdef _DEBUG_IRQ
			lda VIC_BASE+15
			sta frm0
			and #$F8
			sta frm1
			ora #WHITE
			sta frm2
			lda frm1
			ora #RED
			sta frm3
			lda frm1
			ora #YELLOW
			sta frm4
.endif			
			cli					; go
	
main_loop:	jsr execloop
			jmp main_loop

main_irq:	jsr execirq
			jsr soundirq
			jmp IRQ_TAIL

execloop:	jmp (stateptr)

setupgame:	jsr waitframe	; synch frame
			jsr nextfrm		; switch to next frame
			jsr readjoy		; read joysticks
			jsr setgame		; update game state
			jsr calcspr		; prepare objects
			jsr drawfrm		; draw frame
			jsr setdone
			beq @done
			jsr soundoff
			ld16 stateptr, ingame
			jmp startgame
@done:		rts


ingame:		jsr waitframe	; synch frame
			jsr nextfrm		; switch to next frame
.ifdef _DEBUG_IRQ
		lda frm1			; BLACK
		sta VIC_BASE+15
.endif
			jsr readjoy		; read joysticks
.ifdef _DEBUG_IRQ
		lda frm2			; WHITE
		sta VIC_BASE+15
.endif
			jsr execgame	; update game state
.ifdef _DEBUG_IRQ
		lda frm3			; RED
		sta VIC_BASE+15
.endif
			jsr calcspr		; prepare objects
.ifdef _DEBUG_IRQ
		lda frm4			; YELLOW
		sta VIC_BASE+15
.endif
			jsr drawfrm		; draw frame
.ifdef _DEBUG_IRQ
		lda frm0			; OFF
		sta VIC_BASE+15
.endif
			jsr gameover
			bne @next
			jmp gamedone			
@next:		jsr check_key
			beq @done
			ld16 stateptr, setupgame
			jmp initgame
@done:		rts

gamedone:	jsr show_winner
@poll:		jsr check_key
			beq @poll
			ld16 stateptr, setupgame
			jsr initfrm
			jsr initspr
			jmp initgame
			

check_key:	; check key
			ldx VIA2_BASE+0
			lda #0
			sta VIA2_BASE+0
			lda VIA2_BASE+1
			stx VIA2_BASE+0
			cmp #$FF
			rts

readjoy:	; read joysticks
@jbase:		jsr jread8
			jmp jread0
	adaptr = @jbase+1

	.segment "BSS"
	
frm0:		.res 1 
frm1:		.res 1
frm2:		.res 1
frm3:		.res 1
frm4:		.res 1
